package com.das.mechanic_base.mvp.view.sivetain;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.intensivetain.X3SiveTainAdapter;
import com.das.mechanic_base.adapter.maintain.X3TainCancelAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneImageAndRecordBean;
import com.das.mechanic_base.bean.alone.CloseWebviewAcivityBean;
import com.das.mechanic_base.bean.app.BrandMechanicBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.common.UploadVideoBean;
import com.das.mechanic_base.bean.create.SaveWorkSuccessBean;
import com.das.mechanic_base.bean.create.ServiceInfoBean;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.bean.live.FetchLiveBean;
import com.das.mechanic_base.bean.maintain.AdvanceTimeBean;
import com.das.mechanic_base.bean.maintain.CancelWorkBean;
import com.das.mechanic_base.bean.maintain.WorkBaseHeaderBean;
import com.das.mechanic_base.bean.processsive.ProcessSiveTempLetBean;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.gen.WorkNewImageBean;
import com.das.mechanic_base.mvp.contract.sivetain.IntentSiveContract;
import com.das.mechanic_base.mvp.presenter.sivetain.IntentSivePrestener;
import com.das.mechanic_base.mvp.view.camera.X3CameraPhotoActivity;
import com.das.mechanic_base.mvp.view.processnew.X3NewProcessShowNewActivity;
import com.das.mechanic_base.service.UploadVideoService;
import com.das.mechanic_base.utils.FusedLocationUtils;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3BaseDialogUtil;
import com.das.mechanic_base.utils.X3GlideNewUtils;
import com.das.mechanic_base.utils.X3Permission;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3BottomStaffDialog;
import com.das.mechanic_base.widget.X3CancelPopUpWindow;
import com.das.mechanic_base.widget.X3HomeNoticePop;
import com.das.mechanic_base.widget.X3MarqueeText;
import com.das.mechanic_base.widget.X3MemberButtonView;
import com.das.mechanic_base.widget.X3PointDialog;
import com.das.mechanic_base.widget.X3SelectLiveTypeDialog;
import com.das.mechanic_base.widget.X3WorkNoticeDialog;
import com.google.android.material.appbar.AppBarLayout;
import com.umeng.analytics.MobclickAgent;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.IFloatWindowImpl;
import com.yhao.floatwindow.MoveType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.das.mechanic_base.def.mainnewsive.MainNewSiveCompleteStatusDef.ADVANCE_TO_WORK;
import static com.das.mechanic_base.def.mainnewsive.MainNewSiveCompleteStatusDef.ALREADY_FINISH_CHECK_WORK;
import static com.das.mechanic_base.def.mainnewsive.MainNewSiveCompleteStatusDef.NO_ANSWER_NO_FINISH;


/**
 * 新版的工艺工序
 * 什么时候可以自动提交图片？
 * 1.第一次全部答完点击上传答案
 * 2.第一次全部答完点击上传答案 但是没有等待上传完毕回退到上一页面 再次进入
 * 3.已经提交过的答案 再次修改 并且所有题目是已经答完的状态
 * 4.已经提交过的答案 再次修改 但是没有等待上传完毕回退到上一页面 再次进入
 */
@Route(path = X3AppRouterConstants.Router.MAIN_SIVE)
public class X3MainNewSiveTainActivity extends X3BaseActivity<IntentSivePrestener> implements IntentSiveContract.View, X3CancelPopUpWindow.IOpenCameraClick, X3SiveTainAdapter.IOnItemClick, X3TainCancelAdapter.IOnClick, X3MemberButtonView.IOnClickAffirm, X3BottomStaffDialog.IOnSaveWorkBase {

    @BindView(R2.id.rlv_main_tain)
    RecyclerView rlv_main_tain;
    @BindView(R2.id.iv_cancel)
    ImageView iv_cancel;
    @BindView(R2.id.tv_title)
    X3MarqueeText tv_title;
    @BindView(R2.id.btn_submit)
    X3MemberButtonView btn_submit;
    @BindView(R2.id.btn_before)
    X3MemberButtonView btn_before;
    @BindView(R2.id.app_bar)
    AppBarLayout app_bar;
    @BindView(R2.id.cl_header)
    CoordinatorLayout cl_header;
    @BindView(R2.id.iv_header_one)
    ImageView iv_header_one;
    @BindView(R2.id.iv_header_two)
    ImageView iv_header_two;
    @BindView(R2.id.tv_header_one)
    TextView tv_header_one;
    @BindView(R2.id.tv_header_two)
    TextView tv_header_two;
    @BindView(R2.id.v_header_two)
    View v_header_two;
    @BindView(R2.id.tv_live)
    TextView tv_live;
    @BindView(R2.id.iv_preview)
    ImageView iv_preview;
    @BindView(R2.id.lav)
    LottieAnimationView lav;
    @BindView(R2.id.rl_complete)
    RelativeLayout rl_complete;

    private X3CancelPopUpWindow cancelPopUpWindow;
    private X3SiveTainAdapter siveTainAdapter;
    private List<String> titleList;
    private String carNum;
    private String startTime;
    private String completeTime;
    private long allTime;
    private CountDownTimer timer;
    private X3BaseDialogUtil dialogUtil;
    private List<WorkBaseHeaderBean.StaffBaseEntityListBean> staffList;
    private int status;
    private X3BaseDialogUtil dailogSubmit;
    private X3BaseDialogUtil dislogForbid;

    private String allTitle;

    private List<ProcessSiveTempLetBean> allList = new ArrayList<>();
    private ProcessSiveTempLetBean processSiveTempLetBean;//获取点击题item的数据
    private int position;//获取点击题item的下标

    private long timeOutNum;
    private boolean isChina;

    private boolean isContainMe;
    private long workBaseStatus;
    private String carOwnerName;
    private long carOwnerUserId;
    private long liveRoomId;
    private X3HomeNoticePop noticePop;
    private long carId;
    private long numLeftAmount;
    private long reportStatus;
    private List<UploadVideoBean> uploadVideoList;
    private boolean isUploadVideo =false;
    private boolean isOne;
    private List<CancelWorkBean> cancelList;
    private boolean isNotSupportLive;
    private X3WorkNoticeDialog workNoticeDialog;
    private BrandMechanicBean mechanicBean;
    private X3BottomStaffDialog staffDialog;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_main_new_sive_tain;
    }

    @Override
    protected void initView() {
        isNotSupportLive = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);

        tv_live.setVisibility(isNotSupportLive ? View.GONE : View.VISIBLE);
        cl_header.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);
        X3StatusBarUtil.darkMode(this);
        status = -1;
        initRecycle();
        dailogSubmit = new X3BaseDialogUtil(this, R.layout.publish_process_temp);
        dislogForbid = new X3BaseDialogUtil(this, R.layout.publish_forbid_temp);

        isChina = LanguageUtiles.isZhRCN();
        btn_submit.setiOnClickAffirm(this);
        btn_before.setiOnClickAffirm(() -> {
            if (!isContainMe) {
                X3ToastUtils.showMessage(getString(R.string.x3_user_no_index));
                return;
            }
            // 提前施工
            if (mPresenter != null) {
                mPresenter.updateAdavancService(providerWorkBaseId());
            }
        });

        boolean isFirst = (boolean) SpHelper.getData(X3Constent.WORK_FIRST_SHOW_NOTICE + providerWorkBaseId(), false);
        mechanicBean = X3StringUtils.getBrandMechanicBean();

        if (isFirst || mechanicBean == null) {
            return;
        }
        if (mechanicBean.workFirstRemind) {
            showWorkNoticeDialog(true,mechanicBean.workFirstRemark);
            SpHelper.saveData(X3Constent.WORK_FIRST_SHOW_NOTICE + providerWorkBaseId(), true);
        }
    }

    private void showWorkNoticeDialog(boolean isBefore,String content) {

        if (workNoticeDialog == null) {
            workNoticeDialog = new X3WorkNoticeDialog(this);
        }
        workNoticeDialog.show();
        workNoticeDialog.showWorkNotice(isBefore,content);
        workNoticeDialog.setiOnWorkNotice(() -> {
            btn_submit.reset();
            if (isBefore) {
                return;
            }
            if (mPresenter != null) {
                X3MainNewSiveTainActivity.this.showLoading("");
                mPresenter.completeWorkBase(providerWorkBaseId());
            }
        });
        workNoticeDialog.setOnDismissListener(dialog -> btn_submit.reset());

    }

    private boolean judeButtonStatus(String name) {
        //数据库中查询 必选项是否都选了
        List<WorkNewImageBean> workNewImageBeans = DaoSessionUtils.getInstance().searchWorkNewBeanById(providerWorkBaseId());
        if(X3StringUtils.isListEmpty(workNewImageBeans)){
            return  false;
        }
        for (WorkNewImageBean workNewImageBean : workNewImageBeans){
            if((workNewImageBean.workKey.startsWith(providerWorkBaseId() + name) && workNewImageBean.needPhoto && X3StringUtils.isListEmpty(workNewImageBean.imageList))){//必选项没选
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("施工单详情页");
        if (FloatWindow.get("Live") != null) {
            FloatWindow.get("Live").show();
        }
        if (mPresenter != null) {
            mPresenter.startStoreLiveRoom();
        }

        if (mPresenter != null) {
            showLoading("");
            //查询是否是自己的工位，如果是 在请求工艺
            mPresenter.obtainWorkBase();
        }
        if(mPresenter != null && !isNotSupportLive){
            mPresenter.listLiveUploadVideo(providerWorkBaseId());
        }
    }

    @Override
    public void getWorkBaseHeaderInfo(WorkBaseHeaderBean headerBean) {
        hideLoading();
        if (mPresenter != null) {
            mPresenter.requestTainMain();
        }
        workBaseStatus = headerBean.getWorkBaseStatus();
        //reportStatus
        reportStatus = headerBean.getReportStatus();
        carNum = headerBean.getCarNum();
        startTime = headerBean.getStartTime();
        completeTime = headerBean.getCompleteTime();
        carOwnerName = headerBean.getCarOwnerName();
        carOwnerUserId = headerBean.getCarOwnerUserId();
        liveRoomId = headerBean.getLiveRoomId();
        carId = headerBean.getCarId();

        if (workBaseStatus == 0) {
            //需要点击提前开始
            status = ADVANCE_TO_WORK;
            changeToobarColor(0);
        }else if(workBaseStatus == 1) {
            status = NO_ANSWER_NO_FINISH;
            changeToobarColor(1);
        }else {
            rl_complete.setVisibility(View.GONE);
            status = ALREADY_FINISH_CHECK_WORK;
        }

        titleList = headerBean.getServiceBaseNameList();

        allTitle = "";

        if (titleList != null && titleList.size() > 0) {
            for (int i = 0; i < titleList.size(); i++) {
                if (X3StringUtils.isEmpty(titleList.get(i))) {
                    titleList.remove(i);
                }
            }

            for (int i = 0; i < titleList.size(); i++) {
                if (i == 0) {
                    allTitle = titleList.get(i);
                } else {
                    allTitle = allTitle + ", " + titleList.get(i);
                }
            }
        }

        tv_title.setText(allTitle + "（" + carNum + "）");

        this.staffList = headerBean.getStaffBaseEntityList();
        if (!X3StringUtils.isListEmpty(staffList)) {
            iv_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            tv_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            v_header_two.setVisibility(staffList.size() == 2 ? View.VISIBLE : View.GONE);
            for (int i = 0; i < staffList.size(); i++) {
                if (i == 0) {
                    tv_header_one.setText(staffList.get(i).getName());
                    X3GlideNewUtils.loadCircleImage(this, X3StringUtils.getImageUrl(staffList.get(i).getPortrait()),iv_header_one,R.mipmap.x3_car_owner_header);
                }else {
                    tv_header_two.setText(staffList.get(i).getName());
                    X3GlideNewUtils.loadCircleImage(this, X3StringUtils.getImageUrl(staffList.get(i).getPortrait()),iv_header_two,R.mipmap.x3_car_owner_header);
                }
            }
        }else {
            iv_header_two.setVisibility(View.GONE);
            tv_header_two.setVisibility(View.GONE);
            tv_header_one.setText("");
            iv_header_one.setImageResource(R.mipmap.x3_car_owner_header);
        }

        if (status != ALREADY_FINISH_CHECK_WORK) {
            showServiceTime();
        }else {
            tv_live.setVisibility(View.GONE);
        }
    }

    @Override
    public void getWorkBaseHeaderInfoFail() {
        hideLoading();
    }

    @Override
    public long providerReceiveBaseId() {
        return getIntent().getLongExtra("receiveBaseId", 0L);
    }

    @Override
    public void validStartStepSuccess(boolean isCover) {
        //获取校验结果
        /**
         * isStatus ：false：当前服务有其他技师在操作
         * 第一种：点击服务的时候根据返回的状态判断，提示。
         * 第二种：进入工序详情之后返回false，在点击拍照的时候判断，提示。标准工序：iOnClickTakePicture方法
         * 第三种：同时进入工序详情之后：
         *        1、标准工序看谁先上传照片，另外的技师就提示不能在上传
         *        2、自定义工序看谁先上传照片或者提交工序名称，另外的技师就提示不能在上传
         */
        if (!isCover) {
            X3ToastUtils.showMessage(getString(R.string.x3_state_tips_construction));
            return;
        }
        if(!FusedLocationUtils.isLocServiceEnable(X3MainNewSiveTainActivity.this)){
            FusedLocationUtils.goToLocation(X3MainNewSiveTainActivity.this);//定位服务页面
            return;
        }
        Intent intent = new Intent(this, X3NewProcessShowNewActivity.class);
        intent.putExtra("index", position);
        intent.putExtra("workBean", processSiveTempLetBean);
        intent.putExtra("workBaseId", providerWorkBaseId());
        intent.putExtra("carId",carId);
        startActivity(intent);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
            overridePendingTransition(R.anim.activity_enter, 0);
        }
    }

    @Override
    public void setContainMe(boolean isContainMe) {
        this.isContainMe = isContainMe;
    }

    @Override
    public void setContainMeFail() {
        hideLoading();
    }

    @Override
    public void getStoreLiveRoomSuccess(int size) {
        if (isNotSupportLive) {
            tv_live.setVisibility(View.GONE);
            return;
        }
        if (size == 0) {
            if(FloatWindow.get("Live") != null) {
                FloatWindow.destroy("Live");
            }
            return;
        }
        if (X3Permission.requestPermission(this, 24)) {
            //Log.e("SSSS","弹窗是否有权限:" + (FloatWindow.get("Live") == null));
            if (FloatWindow.get("Live") == null) {
                View liveView = View.inflate(this, R.layout.x3_live_float_view,null);
                FloatWindow
                        .with(getApplicationContext())
                        .setView(liveView)
                        .setParentHeight(X3ScreenUtils.getScreenHeight(this))
                        .setTag("Live")
                        .setMoveType(MoveType.slide)
                        .setX(X3ScreenUtils.getScreenWidth(this) - X3ScreenUtils.dipToPx(105,this))  //设置控件初始位置
                        .setY(X3ScreenUtils.getScreenHeight(this) * 8 / 10)
                        .setDesktopShow(false)
                        .build();
            }

            if (FloatWindow.get("Live") != null && liveRoomId != 0) {
                FloatWindow.get("Live").show();
            }

            View live1 = FloatWindow.get("Live").getView();
            if (live1 != null) {
                X3MarqueeText tv_content = live1.findViewById(R.id.tv_content);
                tv_content.setText(getString(R.string.x3_live_on));
                ImageView iv_icon = live1.findViewById(R.id.iv_icon);
                Glide.with(this).asGif().load(R.drawable.x3_live_play).into(iv_icon);
            }


            IFloatWindowImpl live = (IFloatWindowImpl) FloatWindow.get("Live");
            if (live == null) {
                return;
            }
            live.setiOnClickFloat(() -> {
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_CAR_LIST,null);
            });
        }
    }

    @Override
    public void jumpComplete() {
        X3MainNewSiveTainActivity.this.hideLoading();

        // 跳转到施工完成页面
        if (isNotSupportLive) {
            if (X3MyApp.getInstance().iAloneEventCallback != null) {
                X3MyApp.getInstance().iAloneEventCallback.iOnCompleteWork(providerWorkBaseId(),"");
            }
            finish();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putLong("workBaseId", providerWorkBaseId());
        bundle.putLong("carId",carId);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.WORK_FINISH,bundle);
        finish();

    }

    @Override
    public void getLiveInfoSuccess(FetchLiveBean fetchLiveBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("FetchLiveBean",fetchLiveBean);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_MAIN,bundle);
    }

    @Override
    public void getUploadVideoSuccess(List<UploadVideoBean> uploadVideoBean) {
        uploadVideoList = uploadVideoBean;
    }

    @Override
    public void getWorkBaseSuccess(ServiceInfoBean.WorkBaseBean workBaseBean) {
        if (workBaseBean == null) {
            return;
        }
        workBaseBean.workBaseId = providerWorkBaseId();
        staffDialog = new X3BottomStaffDialog(this);
        staffDialog.setiOnSaveWork(this);
        staffDialog.show();
        staffDialog.assignStaff(workBaseBean,false);
    }

    /**
     * 根据返回的时间，判断施工前，提前施工，结束施工等状态
     */
    private void showServiceTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        String nowTime = simpleDateFormat.format(date);
        try {
            long startLong = X3TimeUtils.stringToLong(startTime, "yyyy-MM-dd HH:mm:ss");//开始施工事件
            long endLong = X3TimeUtils.stringToLong(completeTime, "yyyy-MM-dd HH:mm:ss");//施工结束事件
            long nowLong = X3TimeUtils.stringToLong(nowTime, "yyyy-MM-dd HH:mm:ss");//当前系统时间
            allTime = endLong - startLong;
            long resultLong = endLong - nowLong;
            long isStartLong = nowLong - startLong;

            //如果还没有开始，那么显示可提前开始施工
            if (isStartLong < 0) {
                // 还没开始
                changeToobarColor(0);
                tv_live.setVisibility(View.GONE);
                //countComeTime(allTime);
            } else {
                tv_live.setVisibility((liveRoomId == 0 && !isNotSupportLive) ? View.VISIBLE : View.GONE);
                if (resultLong > 0) {
                    changeToobarColor(1);
                    countTime(resultLong);
                } else {
                    // 当前已经超时了
                    /**
                     * 超时计算超时时间
                     */
                    timeOutNum = nowLong - endLong;

                    changeToobarColor(2);
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void countTime(long resultLong) {
        if (resultLong < 0) {
            changeToobarColor(2);
        } else {
            countDownTime(resultLong);
        }
    }

    /**
     * 施工时间倒计时
     *
     * @param seconds
     */
    private void countDownTime(long seconds) {

        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimer(seconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {


            }

            @Override
            public void onFinish() {
                if (isFinishing()) {
                    return;
                }
                changeToobarColor(2);
            }
        };
        timer.start();
    }

    @Override
    protected IntentSivePrestener createPresenter() {
        return new IntentSivePrestener();
    }

    private void initRecycle() {
        rlv_main_tain.setLayoutManager(new LinearLayoutManager(this));
        siveTainAdapter = new X3SiveTainAdapter(this);
        rlv_main_tain.setAdapter(siveTainAdapter);
        siveTainAdapter.setIOnClickItem(this);
    }

    @OnClick({R2.id.iv_back, R2.id.iv_cancel,R2.id.tv_live,R2.id.tv_one,R2.id.iv_preview})
    public void onMainNewViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_cancel) {
            if (cancelPopUpWindow == null) {
                cancelPopUpWindow = new X3CancelPopUpWindow(this);
            }
            cancelPopUpWindow.showPopupWindow(iv_cancel, isshowred);
            cancelPopUpWindow.providerReceive(providerReceiveBaseId(), providerWorkBaseId(), 1);
            cancelPopUpWindow.setiOnItemCameraClick(this);
            cancelPopUpWindow.showWorkStatus(workBaseStatus);
        } else if (id == R.id.tv_live) {//                Intent intent = new Intent(this, LiveScanActivity.class);
//                intent.putExtra("workBaseId",providerWorkBaseId());
//                intent.putExtra("canLive",1);
//                startActivity(intent);
            X3SelectLiveTypeDialog selectLiveTypeDialog = new X3SelectLiveTypeDialog(X3MainNewSiveTainActivity.this);
            selectLiveTypeDialog.show();
            selectLiveTypeDialog.setIonSelectOnclick(new X3SelectLiveTypeDialog.IonSelectClickListener() {
                @Override
                public void iOnselectOther() {//扫描二维码
                    SpHelper.saveData("livetype", 1);
                    Bundle bundle = new Bundle();
                    bundle.putLong("workBaseId", providerWorkBaseId());
                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.LIVE_SCAN,bundle);
                }

                @Override
                public void iOnselectLocal() {//本机直播
                    SpHelper.saveData("livetype", 0);
                    X3PointDialog pointDialog = new X3PointDialog(X3MainNewSiveTainActivity.this, "", getString(R.string.confirm_go_live), getString(R.string.x3_cancel_info) + "", getString(R.string.x3_affirm_info));
                    pointDialog.show();
                    pointDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                        @Override
                        public void iBtnAffirmClick() {
                            if (mPresenter != null) {
                                mPresenter.generateLiveInfoOnLocal(carId, true, providerWorkBaseId());
                            }
                        }

                        @Override
                        public void iBtnCancelClick() {

                        }
                    });
                }

                @Override
                public void iOnselectUploadVideo() {//上传视频
                    int workBaseId = (int) SpHelper.getData("workBaseId" + providerWorkBaseId(), 0);
                    if ((workBaseId != 0 && workBaseId == providerWorkBaseId()) || (!X3StringUtils.isListEmpty(uploadVideoList) && uploadVideoList.size() > 0)) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("workBaseId", providerWorkBaseId());
                        bundle.putLong("carId", carId);
                        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.UPLOAD_VIDEO,bundle);

                    } else {
                        isUploadVideo = true;
                        Intent intent = new Intent(X3MainNewSiveTainActivity.this, X3CameraPhotoActivity.class);
                        intent.putExtra("isAlbum", 1);
                        intent.putExtra("allNum", 1);
                        intent.putExtra("showVideo", 1);
                        startActivity(intent);
                        overridePendingTransition(R.anim.activity_enter, 0);
                    }

                }
            });
        } else if (id == R.id.tv_one) {
            if (noticePop == null) {
                noticePop = new X3HomeNoticePop(this, getString(R.string.x3_work_recode), getString(R.string.x3_work_recode_notice));
            }
            noticePop.fromType(1);
            noticePop.show();
        } else if (id == R.id.iv_preview) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title", "施工单施工报告预览页");
            bundle.putString("path", X3Constent.HOME_FINISH_DETAIL_URL + "id=" + providerWorkBaseId() + "&source=APP");
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        }
    }

    //点击取消施工
    @Override
    public void iOnClick() {
        // 取消施工 先请求能取消的项目
        if (mPresenter != null) {
            mPresenter.getCancelWork();
        }
    }

    @Override
    public void iOnJumpToWorkDetail() {
        switch ((int) workBaseStatus) {
            case 0:
            case 1:
                if (mPresenter != null) {
                    mPresenter.getWorkBase();
                }
                break;
            default:
                Bundle bundle = new Bundle();
                bundle.putBoolean("isDark",true);
                bundle.putString("title","施工单详情页");
                bundle.putString("path", X3Constent.MAIN_TAIN_ADD_WORK + "workBaseId=" + providerWorkBaseId());
                X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
                break;
        }
    }

    //点击条目进入答题
    @Override
    public void iOnItemClickListener(ProcessSiveTempLetBean siveTempLetBean, int positions) {
        if (!X3Utils.isFastClick()) {
            return;
        }

        if (workBaseStatus > 1) {
            X3ToastUtils.showMessage(getString(R.string.x3_work_order_incorrect));
            return;
        }

        if (!isContainMe) {
            X3ToastUtils.showMessage(getString(R.string.x3_user_no_index));
            return;
        }

        this.processSiveTempLetBean = siveTempLetBean;
        this.position = positions;
        if (status == ADVANCE_TO_WORK) {
            X3ToastUtils.showMessage(getString(R.string.x3_update_work_to_do));
            return;
        }
        //先校验获取是否是多人答题
        if (mPresenter != null) {
            mPresenter.validStartStep(siveTempLetBean.sn);
        }
    }

    @Override
    public long providerWorkBaseId() {
        return getIntent().getLongExtra("id", 0L);
    }

    @Override
    public void saveTechnicsTempletList(List<ProcessSiveTempLetBean> mList) {
        hideLoading();
        this.allList = mList;

        for (int i =0; i < mList.size(); i++) {
            numLeftAmount = 0;
             // 车辆确认
                WorkNewImageBean workNewImageBean = DaoSessionUtils.getInstance().searchWorkNewBean(providerWorkBaseId() + mList.get(i).name + getString(R.string.x3_car_take_photo));
                    if (workNewImageBean != null) {
                        List<AloneImageAndRecordBean> imageList = workNewImageBean.imageList;
                            if(!X3StringUtils.isListEmpty(imageList)){
                               numLeftAmount++;
                        }
                }

                //产品确认
                WorkNewImageBean workNewImageBean1 = DaoSessionUtils.getInstance().searchWorkNewBean(providerWorkBaseId() + mList.get(i).name + getString(R.string.x3_product_confirmation));
                    if (workNewImageBean1 != null) {
                        List<AloneImageAndRecordBean> imageList = workNewImageBean1.imageList;
                        if(!X3StringUtils.isListEmpty(imageList)){
                            numLeftAmount++;
                        }
                    }

                //施工前过程
                WorkNewImageBean workNewImageBeanbefore = DaoSessionUtils.getInstance().searchWorkNewBean(providerWorkBaseId() + mList.get(i).name + getString(R.string.x3_situation_before_construction));
                    if (workNewImageBeanbefore != null) {
                        List<AloneImageAndRecordBean> imageList = workNewImageBeanbefore.imageList;
                        if(!X3StringUtils.isListEmpty(imageList)){
                            numLeftAmount++;
                        }
                   }

                List<WorkNewImageBean> workNewImagelist = DaoSessionUtils.getInstance().searchWorkNewBeanById(providerWorkBaseId());
                    boolean isAll = false;
                    for (WorkNewImageBean workNewImageBeans : workNewImagelist) {
                       //施工过程
                        if (!workNewImageBeans.workKey.startsWith(providerWorkBaseId() + mList.get(i).name + getString(R.string.x3_situation_construction))) {
//                            isAll = false;
                            continue;
                        }
                        List<AloneImageAndRecordBean> imageList = workNewImageBeans.imageList;
                        if (X3StringUtils.isListEmpty(imageList)) {
//                            isAll = false;
                            continue;
                        }else {
                            isAll = true;
                        }
                    }

                if (isAll) {
                    numLeftAmount++;
                }

                //施工后过程
                WorkNewImageBean workNewImageBeanafter = DaoSessionUtils.getInstance().searchWorkNewBean(providerWorkBaseId() + mList.get(i).name + getString(R.string.x3_situation_after_construction));
                if (workNewImageBeanafter != null) {
                    List<AloneImageAndRecordBean> imageList = workNewImageBeanafter.imageList;
                    if(!X3StringUtils.isListEmpty(imageList)){
                        numLeftAmount++;
                    }
                }

                //拆件确认
                WorkNewImageBean workNewImageBeanafterdisa = DaoSessionUtils.getInstance().searchWorkNewBean(providerWorkBaseId() + mList.get(i).name + getString(R.string.situation_affirm));
                if (workNewImageBeanafterdisa != null) {
                    List<AloneImageAndRecordBean> imageList = workNewImageBeanafterdisa.imageList;
                    if(!X3StringUtils.isListEmpty(imageList)){
                        numLeftAmount++;
                    }
                }

                mList.get(i).num = numLeftAmount;
        }

        if (siveTainAdapter != null) {
            siveTainAdapter.ChangeAloneTitle(mList);
        }

        btn_submit.changeBtnStatus(judeLeftAmount());
    }

    private boolean judeLeftAmount() {
        if (X3StringUtils.isListEmpty(allList)) {
            return false;
        }
        for (int i = 0 ; i < allList.size(); i++ ){
            if(allList.get(i).leftPhotoAmount <= 0 || !judeButtonStatus(allList.get(i).name)){
                return false;
            }
        }
        return true;
    }

    private Handler mHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            timeOutNum += 1000;
            mHandler.postDelayed(this,1000);
        }
    };

    @Override
    public void requestCancelWorkSuccess(List<CancelWorkBean> cancelWorkBeans) {
        //取消服务项目
        dialogUtil = X3BaseDialogUtil.showDialog(this, R.layout.x3_tain_cancel_service);
        RecyclerView rl_service = dialogUtil.getView(R.id.rl_view);
        dialogUtil.getView(R.id.btn_cancel).setOnClickListener(view -> {
            if (dialogUtil != null) {
                dialogUtil.dismiss();
            }
        });

        dialogUtil.getView(R.id.btn_affirm).setOnClickListener(view -> {
            if (X3StringUtils.isListEmpty(cancelList)) {
                X3ToastUtils.showMessage(getString(R.string.x3_please_select_cancel_work));
                return;
            }
            if (dialogUtil != null) {
                dialogUtil.dismiss();
            }
            if (mPresenter != null) {
                mPresenter.affirmCancelWork(cancelList, isOne);
            }
        });

        rl_service.setLayoutManager(new LinearLayoutManager(this));
        X3TainCancelAdapter tainServiceAdapter = new X3TainCancelAdapter(this, cancelWorkBeans);
        rl_service.setAdapter(tainServiceAdapter);
        tainServiceAdapter.setiOnClick(this);
    }

    @Override
    public void changeServiceName(List<String> serviceNameList) {
        X3ToastUtils.showMessage(getString(R.string.x3_cancel_success));
        EventBus.getDefault().post("UPDATE_CNACEL_ORDER");
        String title = null;

        titleList.removeAll(serviceNameList);

        for (int i = 0; i < titleList.size(); i++) {
            if (i == 0) {
                title = titleList.get(i);
            } else {
                title = title + "-" + titleList.get(i);
            }
        }

        tv_title.setText(title + "");

        if (mPresenter != null) {
            //取消成功之后刷新剩余时间
            mPresenter.obtainWorkBase();
            //取消成功之后刷新工序list
            //mPresenter.requestTainMain();
        }
    }

    @Override
    public void finishCurrent() {
        X3ToastUtils.showMessage(getString(R.string.x3_cancel_success));
        //取消成功，返回上个页面刷新的标示
        EventBus.getDefault().post("UPDATE_CANCEL_ORDER");
        //关闭上一个施工和返回施工单界面
        EventBus.getDefault().post(new CloseWebviewAcivityBean());
        if (X3MyApp.getInstance().iAloneEventCallback != null) {
            X3MyApp.getInstance().iAloneEventCallback.iOnCancelWork(providerWorkBaseId(),"");
        }
        finish();
    }

    @Override
    public void updateAfterWork(boolean isFlag, AdvanceTimeBean advanceTimeBean) {
        EventBus.getDefault().post("UPDATE_START_ORDER");
        DeleteFriends deleteFriends = new DeleteFriends("UPDATE_START_ORDER");
        EventBus.getDefault().post(deleteFriends);
        startTime = advanceTimeBean.getStartTime();
        completeTime = advanceTimeBean.getCompleteTime();

        showServiceTime();
        if (mPresenter != null) {
            mPresenter.requestTainMain();
        }
    }

    @Override
    public void iCancelOnClickListener(List<CancelWorkBean> mList, boolean isOne) {
        this.isOne = isOne;
        this.cancelList = mList;
    }

    private void changeToobarColor(int status) {
        switch (status) {
            case 0:
                this.status = ADVANCE_TO_WORK;
                btn_submit.setVisibility(View.INVISIBLE);
                btn_before.setVisibility(View.VISIBLE);
                btn_before.changeBtnStatus(isContainMe);

                break;
            case 1:
                this.status = NO_ANSWER_NO_FINISH;
                btn_submit.setVisibility(View.VISIBLE);
                btn_before.setVisibility(View.GONE);
                btn_submit.changeBtnStatus(judeLeftAmount());

                break;
            case 2:
                this.status = NO_ANSWER_NO_FINISH;
                if (mHandler != null) {
                    mHandler.removeCallbacks(runnable);
                }
                mHandler.post(runnable);

                btn_submit.setVisibility(View.VISIBLE);
                btn_before.setVisibility(View.GONE);
                btn_submit.changeBtnStatus(judeLeftAmount());

                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        if (dialogUtil != null) {
            dialogUtil.dismiss();
        }
        if (dislogForbid != null) {
            dislogForbid.dismiss();
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     *发布
     */
    @Override
    public void iOnClickAffirm() {

        if (mechanicBean == null) {
            if (mPresenter != null) {
                mPresenter.completeWorkBase(providerWorkBaseId());
            }
            return;
        }
        if (!mechanicBean.workCompleteRemind) {
            if (mPresenter != null) {
                mPresenter.completeWorkBase(providerWorkBaseId());
            }
            return;
        }
        boolean isFirst = (boolean) SpHelper.getData(X3Constent.WORK_FIRST_SUBMIT_NOTICE + providerWorkBaseId(), false);
        mechanicBean = X3StringUtils.getBrandMechanicBean();

        if (isFirst || mechanicBean == null) {
            if (mPresenter != null) {
                mPresenter.completeWorkBase(providerWorkBaseId());
            }
            return;
        }
        if (mechanicBean.workFirstRemind) {
            showWorkNoticeDialog(false,mechanicBean.workCompleteRemark);
            SpHelper.saveData(X3Constent.WORK_FIRST_SHOW_NOTICE + providerWorkBaseId(), true);
        }else {
            if (mPresenter != null) {
                mPresenter.completeWorkBase(providerWorkBaseId());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("施工单详情页");
        if (mPresenter != null) {
            mPresenter.endStoreLiveRoom();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //相册返回 集合
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                List<String> pList = (List<String>) cameraBean.cameraData;
                if (X3StringUtils.isListEmpty(pList)) {
                    return;
                }

                if(isUploadVideo){
                    SpHelper.saveData("workBaseId"+providerWorkBaseId(),pList.get(0));

                    Bundle bundle = new Bundle();
                    bundle.putString("path",pList.get(0));
                    bundle.putLong("workBaseId",providerWorkBaseId());
                    bundle.putLong("carId",carId);
                    X3RouterCenter.startNavigate(X3AppRouterConstants.Router.UPLOAD_VIDEO,bundle);


                    Intent intent1 = new Intent(X3MainNewSiveTainActivity.this, UploadVideoService.class);
                    intent1.putExtra("path",pList.get(0));
                    intent1.putExtra("carId",carId);
                    intent1.putExtra("workBaseId",providerWorkBaseId());
                    intent1.putExtra("isGoon",true);
                    startService(intent1);
                }

                break;
            default:
                break;
        }
    }

    private boolean isshowred = false;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(String data) {
        switch (data){
            case "isshowred":
                isshowred = true;
                lav.setVisibility(View.VISIBLE);
                lav.setAnimation("data001.json");
                lav.setRepeatCount(Animation.INFINITE);
                lav.playAnimation();
                break;

            case "iscancelshowred":
                lav.cancelAnimation();
                lav.setVisibility(View.GONE);
                isshowred = false;

                break;
        }
    }

    @Override
    public void iOnSaveWorkSuccess(SaveWorkSuccessBean successBean,boolean isDetection) {
        iOnRefreshData();
    }

    @Override
    public void iOnRefreshData() {
        DeleteFriends deleteFriends = new DeleteFriends("refresh");
        EventBus.getDefault().post(deleteFriends);
        onResume();
    }
}
